# -*- coding: utf-8 -*-
# kay_authsub.views

import os.path
import kay
from kay.conf import settings
from kay.i18n import gettext as _
from kay.auth.decorators import login_required
from werkzeug import (
  Response, redirect
)
from gdata.client import GDClient
from gdata import gauth

from kay_authsub.utils import (
  get_authsub_url, get_revoke_authsub_url, is_devserver,
)

from kay_authsub.models import Token
from kay_authsub.utils import (
  get_authsub_token_from_request, save_authsub_token, delete_authsub_token
)  

# Create your views here.

@login_required
def receive_authsub_token(request):
  client = GDClient()
  client.ssl = True
  if is_devserver:
    authsub_token = gauth.AuthSubToken.from_url(request.url)
  else:
    key_file = getattr(settings, "AUTHSUB_PRIVATE_KEY", None)
    if key_file:
      rsa_key = file(os.path.join(kay.PROJECT_DIR, key_file)).read()
      authsub_token = gauth.SecureAuthSubToken.from_url(request.url, rsa_key)
    else:
      authsub_token = gauth.AuthSubToken.from_url(request.url)
  if authsub_token.token_string:
    access_token = client.upgrade_token(authsub_token)
    save_authsub_token(access_token, request)
  next = request.args.get("next", "/")
  return redirect(next)

@login_required
def revoke_authsub_token(request):
  authsub_token = get_authsub_token_from_request(request)
  client = GDClient()
  client.ssl = True
  client.revoke_token(authsub_token)
  delete_authsub_token(request)
  next = request.args.get("next", "/")
  return redirect(next)
